const mysql = require('mysql2/promise');
const jwt = require('jsonwebtoken');
const { secret } = require('../config/jwt');

async function testAPI() {
  console.log('🔍 开始测试API...\n');

  // 创建数据库连接
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'uni_library'
  });

  try {
    // 1. 获取测试用户
    console.log('👤 获取测试用户...');
    const [users] = await connection.execute('SELECT id, username FROM users LIMIT 1');
    if (users.length === 0) {
      console.log('❌ 没有用户，请先创建用户');
      return;
    }
    const user = users[0];
    console.log(`✅ 找到用户: ${user.username} (ID: ${user.id})`);

    // 2. 获取测试图书
    console.log('\n📚 获取测试图书...');
    const [books] = await connection.execute('SELECT id, name FROM books LIMIT 1');
    if (books.length === 0) {
      console.log('❌ 没有图书，请先添加图书');
      return;
    }
    const book = books[0];
    console.log(`✅ 找到图书: ${book.name} (ID: ${book.id})`);

    // 3. 测试书架添加
    console.log('\n📖 测试书架添加API...');
    try {
      // 首先检查是否已在书架中
      const [existing] = await connection.execute(
        'SELECT id FROM bookshelf WHERE user_id = ? AND book_id = ?',
        [user.id, book.id]
      );

      if (existing.length > 0) {
        console.log('ℹ️  图书已在书架中，跳过添加');
      } else {
        // 添加到书架
        await connection.execute(
          'INSERT INTO bookshelf (user_id, book_id) VALUES (?, ?)',
          [user.id, book.id]
        );
        console.log('✅ 书架添加成功');
      }
    } catch (error) {
      console.log('❌ 书架添加失败:', error.message);
    }

    // 4. 测试借阅
    console.log('\n📖 测试借阅API...');
    try {
      // 检查图书库存
      const [stock] = await connection.execute('SELECT stock FROM books WHERE id = ?', [book.id]);
      if (stock[0].stock <= 0) {
        console.log('ℹ️  图书库存不足，跳过借阅测试');
      } else {
        // 检查是否已借阅
        const [borrowed] = await connection.execute(
          'SELECT id FROM borrow_records WHERE user_id = ? AND book_id = ? AND status = "borrowed"',
          [user.id, book.id]
        );

        if (borrowed.length > 0) {
          console.log('ℹ️  已借阅此书，跳过借阅测试');
        } else {
          // 执行借阅
          const dueDate = new Date();
          dueDate.setDate(dueDate.getDate() + 30);

          await connection.execute(
            'INSERT INTO borrow_records (user_id, book_id, borrow_date, due_date, borrow_days, status) VALUES (?, ?, NOW(), ?, ?, ?)',
            [user.id, book.id, dueDate.toISOString().split('T')[0], 30, 'borrowed']
          );

          // 减少库存
          await connection.execute('UPDATE books SET stock = stock - 1 WHERE id = ?', [book.id]);

          console.log('✅ 借阅测试成功');
        }
      }
    } catch (error) {
      console.log('❌ 借阅测试失败:', error.message);
    }

    console.log('\n🎉 API测试完成！');

  } catch (error) {
    console.error('❌ 测试失败:', error);
  } finally {
    await connection.end();
  }
}

// 运行测试
testAPI().catch(console.error);
